package org.peoples.net {
	
	import com.qualityattributes.collections.queues.ArrayQueue;
	import com.qualityattributes.utils.IIterator;
	
	import flash.errors.IOError;
	import flash.events.AsyncErrorEvent;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.NetStatusEvent;
	import flash.net.NetConnection;
	import flash.net.ObjectEncoding;
	import flash.net.Responder;
	
	public class PeoplesConnection extends NetConnection {
		
		private var callQueue:ArrayQueue;
		
		public function PeoplesConnection():void {
			
			this.callQueue = new ArrayQueue();
			
			objectEncoding = ObjectEncoding.AMF0;
			
		}
		
		public override function call(command:String, responder:Responder, ... arguments):void {
			if (!connected) {
				this.callQueue.add( new CallQueueItem(command, responder, arguments) );
				return;
			}
			
			super.call(command, responder, arguments);
		}
		
		private function callQueuedCommands():void {
			var itr:IIterator = callQueue.iterator();
			while (itr.hasNext()) {
				var item:CallQueueItem = itr.next() as CallQueueItem;
				this.call(item.command, item.responder, item.args);
			}
		}
		
		private function onResult(result:Object):void {
			//
		}
		
		private function onFault(fault:Object):void {
			//
		}
		
		private function onAsyncError(evt:AsyncErrorEvent):void {
			var new_evt:AsyncErrorEvent = new AsyncErrorEvent(evt.type, evt.bubbles, evt.cancelable, evt.text, evt.error);
			dispatchEvent(new_evt);
		}
		
		private function onIOError(evt:IOErrorEvent):void {
			var new_evt:IOErrorEvent = new IOErrorEvent(evt.type, evt.bubbles, evt.cancelable, evt.text);
			dispatchEvent(new_evt);
		}
		
		private function onNetStatus(evt:NetStatusEvent):void {
			var new_evt:NetStatusEvent = new NetStatusEvent(evt.type, evt.bubbles, evt.cancelable, evt.info);
			dispatchEvent(new_evt);
			
			if (evt.info.code == "NetConnection.Connect.Success") {
				callQueuedCommands();
			}
		}
		
	}
	
}